package tool

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/pmylund/sortutil"
)

//timeList type of timeList
type TimeList []time.Time

//FormatIssueLen return the string of indexNumber suffix formatted
//Those with less than 3 digits fill in with 0
func (t TimeList) FormatIssueSuffix(indexNumber int) string {
	var minLen = 3
	lengthDay := len(strconv.Itoa(t.TotalOneDayIssue()))
	if lengthDay < minLen {
		lengthDay = minLen
	}
	fmtStr := strings.Replace(`%0{len}d`, "{len}", strconv.Itoa(lengthDay), -1)
	return fmt.Sprintf(fmtStr, indexNumber)
}

//TotalOneDayIssue return the number of one day issues
func (t TimeList) TotalOneDayIssue() (issueNumber int) {
	return len(t)
}

//GetIndex give a separate time firstTime,firstTime in timeList's index = 1
//listB add 1 day and sort and append listA,return index of the timeValue
func (t TimeList) GetIndex(firstTime, timeValue time.Time) (index int) {
	var listA = make(TimeList, 0, len(t))
	for _, tv := range t {
		if tv.Before(firstTime) {
			listA = append(listA, tv.Add(time.Hour*24))
		} else {
			listA = append(listA, tv)
		}
	}
	sortutil.Asc(listA)
	for i, value := range listA {
		if timeValue.Format("15:04:05") == value.Format("15:04:05") {
			index = i + 1
		}
	}
	if index == 0 {
		panic("cannot find indexOf timeList")
	}
	return
}

//Min return the minimum time of list
func (t TimeList) Min() time.Time {
	if len(t) == 0 {
		panic("empty timeList")
	}
	m := t[0]
	for _, tv := range t {
		if tv.Before(m) {
			m = tv
		}
	}
	return m
}

//Max return the Maximum time of list
func (t TimeList) Max() time.Time {
	if len(t) == 0 {
		panic("empty timeList")
	}
	m := t[0]
	for _, tv := range t {
		if tv.After(m) {
			m = tv
		}
	}
	return m
}

//CurrentTime return lotto current open time
func (t TimeList) CurrentTime() time.Time {
	tmpList := make(TimeList, 0)
	for _, ta := range t {
		if ta.After(time.Now()) {
			tmpList = append(tmpList, ta)
		}
	}
	if len(tmpList) == 0 {
		return t.Min().AddDate(0, 0, 1)
	}
	return tmpList.Min()
}

//PrevTime return lotto prev open time
func (t TimeList) PrevTime() time.Time {
	tmpList := make(TimeList, 0)
	for _, ta := range t {
		if ta.Before(time.Now()) {
			tmpList = append(tmpList, ta)
		}
	}
	if len(tmpList) == 0 {
		return t.Max().AddDate(0, 0, -1)
	}
	return tmpList.Max()
}
